package com.assess.controller;

import com.assess.entity.AssessIndicator;
import com.assess.service.AssessIndicatorService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.deductive.common.core.domain.AjaxResult;
import com.deductive.common.core.page.TableDataInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.*;

@RestController
@RequestMapping("/assess/indicator")
@Api(tags = "指标树-节点管理")
public class AssessIndicatorController {

    @Resource
    private AssessIndicatorService indicatorService;

    @GetMapping("/tree")
    @ApiOperation("按 rootId 返回整棵指标树")
    public List<TreeNode> tree(@ApiParam("根节点ID") @RequestParam Long rootId) {
        if (rootId == null || rootId <= 0) {
            return Collections.emptyList();
        }
        List<AssessIndicator> list = indicatorService.listByRootId(rootId);
        Map<Long, TreeNode> map = new LinkedHashMap<>();
        for (AssessIndicator a : list) {
            TreeNode n = new TreeNode();
            n.setId(a.getId());
            n.setParentId(a.getParentId());
            n.setName(a.getName());
            n.setIsLeaf(Boolean.TRUE.equals(a.getIsLeaf()));
            map.put(a.getId(), n);
        }
        List<TreeNode> roots = new ArrayList<>();
        for (TreeNode n : map.values()) {
            if (n.getParentId() == null) { roots.add(n); }
            else {
                TreeNode p = map.get(n.getParentId());
                if (p != null) p.getChildren().add(n);
                else roots.add(n);
            }
        }
        return roots;
    }

    @PostMapping
    @ApiOperation("新增")
    public AjaxResult create(@RequestBody AssessIndicator entity) {
        AjaxResult vr = validateIndicator(entity, false);
        if (vr != null) return vr;
        // 唯一性校验：code + (schemeId 可选)
        LambdaQueryWrapper<AssessIndicator> uq = new LambdaQueryWrapper<>();
        uq.eq(AssessIndicator::getCode, entity.getCode())
          .eq(entity.getSchemeId() != null, AssessIndicator::getSchemeId, entity.getSchemeId());
        if (indicatorService.count(uq) > 0) {
            return AjaxResult.error("编码已存在");
        }
        if (entity.getParentId() == null && entity.getRootId() == null) {
            indicatorService.save(entity); // 此时拿到 entity.getId()
            entity.setRootId(entity.getId());
            indicatorService.updateById(entity);
            return AjaxResult.success(entity);
        } else {
            return indicatorService.save(entity) ? AjaxResult.success(entity) : AjaxResult.error("保存失败");
        }
    }

    @PutMapping
    @ApiOperation("修改")
    public AjaxResult update(@RequestBody AssessIndicator entity) {
        if (entity.getId() == null) {
            return AjaxResult.error("ID不能为空");
        }
        AjaxResult vr = validateIndicator(entity, true);
        if (vr != null) return vr;
        // 唯一性校验（排除自身）
        LambdaQueryWrapper<AssessIndicator> uq = new LambdaQueryWrapper<>();
        uq.eq(AssessIndicator::getCode, entity.getCode())
          .eq(entity.getSchemeId() != null, AssessIndicator::getSchemeId, entity.getSchemeId())
          .ne(AssessIndicator::getId, entity.getId());
        if (indicatorService.count(uq) > 0) {
            return AjaxResult.error("编码已存在");
        }
        boolean ok = indicatorService.updateById(entity);
        return ok ? AjaxResult.success() : AjaxResult.error("更新失败");
    }

    @DeleteMapping
    @ApiOperation("批量删除")
    public AjaxResult delete(@ApiParam("ID列表") @RequestParam List<Long> idList) {
        if (idList == null || idList.isEmpty()) {
            return AjaxResult.error("ID列表不能为空");
        }
        boolean ok = indicatorService.removeByIds(idList);
        return ok ? AjaxResult.success() : AjaxResult.error("删除失败");
    }

    @GetMapping("/{id}")
    @ApiOperation("根据ID查询")
    public AjaxResult get(@PathVariable Long id) {
        if (id == null) {
            return AjaxResult.error("ID不能为空");
        }
        AssessIndicator row = indicatorService.getById(id);
        return row != null ? AjaxResult.success(row) : AjaxResult.error("未找到记录");
    }

    @GetMapping("/page")
    @ApiOperation("分页查询")
    public TableDataInfo page(@RequestParam(defaultValue = "1") long pageNum,
                              @RequestParam(defaultValue = "10") long pageSize,
                              @RequestParam(required = false) Long rootId,
                              @RequestParam(required = false) String name) {
        if (pageNum <= 0) pageNum = 1;
        if (pageSize <= 0) pageSize = 10;
        LambdaQueryWrapper<AssessIndicator> qw = new LambdaQueryWrapper<>();
        qw.eq(rootId != null, AssessIndicator::getRootId, rootId)
          .like(name != null && !name.isEmpty(), AssessIndicator::getName, name)
          .orderByAsc(AssessIndicator::getRootId, AssessIndicator::getParentId, AssessIndicator::getOrderNum);
        Page<AssessIndicator> page = indicatorService.page(new Page<>(pageNum, pageSize), qw);
        TableDataInfo rsp = new TableDataInfo();
        rsp.setCode(com.deductive.common.constant.HttpStatus.SUCCESS);
        rsp.setMsg("查询成功");
        rsp.setRows(page.getRecords());
        rsp.setTotal(page.getTotal());
        return rsp;
    }

    private AjaxResult validateIndicator(AssessIndicator e, boolean isUpdate) {
        if (!isUpdate) {
            // 新增根节点：允许 parentId 与 rootId 同为空；其余情况 parentId/rootId 任一应有值
        }
        if (e == null) return AjaxResult.error("参数不能为空");
        if (e.getName() == null || e.getName().trim().isEmpty()) return AjaxResult.error("名称不能为空");
        if (e.getCode() == null || e.getCode().trim().isEmpty()) return AjaxResult.error("编码不能为空");
        if (e.getStatus() == null || (e.getStatus() != 0 && e.getStatus() != 1)) return AjaxResult.error("状态非法");
        if (e.getOrderNum() != null && e.getOrderNum() < 0) return AjaxResult.error("排序号不能为负");
        return null;
    }

    public static class TreeNode {
        private Long id;
        private Long parentId;
        private String name;
        private boolean isLeaf;
        private List<TreeNode> children = new ArrayList<>();
        public Long getId() { return id; }
        public void setId(Long id) { this.id = id; }
        public Long getParentId() { return parentId; }
        public void setParentId(Long parentId) { this.parentId = parentId; }
        public String getName() { return name; }
        public void setName(String name) { this.name = name; }
        public boolean getIsLeaf() { return isLeaf; }
        public void setIsLeaf(boolean isLeaf) { this.isLeaf = isLeaf; }
        public List<TreeNode> getChildren() { return children; }
        public void setChildren(List<TreeNode> children) { this.children = children; }
    }
}


